<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区 -->
        <el-card>
            <!-- 间隙 -->
            <el-row :gutter="20">  
                <!-- 列宽 -->
                <el-col :span="7">
                    <!-- 搜索添加 双向绑定搜索信息 clearable 清除功能  -->
                    <el-input
                            placeholder="请输入内容"
                            clearable
                            @clear="getUserList"
                            v-model="queryInfo.query"
                    >
                        <el-button
                                slot="append"
                                icon="el-icon-search"
                                @click="getUserList"
                        ></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="dialogVisible = true"
                    >添加用户
                    </el-button
                    >
                </el-col>
            </el-row>
            <!-- 用户列表  border 边框 stripe 隔行变色 -->
            <el-table :data="userlist" border stripe style="width: 100%">
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="phone" label="电话"></el-table-column>

                <el-table-column label="角色">
                    <template slot-scope="scope">
                        <div v-for="(item,index) in scope.row.authorities" :key="index">
                            <div> {{ item.name }}</div>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="状态">
                    <template v-slot="scope">
                        <el-switch
                                v-model="scope.row.isActive"
                                @change="userStateChanged(scope.row)"
                        ></el-switch>
                    </template>
                </el-table-column>
                <!--自定义插槽-->
                <el-table-column label="操作">
                    <!-- 编辑用户 -->
                    <template v-slot="scope">
                        <el-button
                                type="primary"
                                icon="el-icon-edit"
                                @click="showEditDialog(scope.row.id)"
                                size="mini"
                        ></el-button>
                        <!-- 分配角色 -->
                        <el-tooltip
                                :enterable="false"
                                effect="dark"
                                content="分配角色"
                                placement="top-start"
                        >
                            <el-button
                                    type="warning"
                                    icon="el-icon-setting"
                                    size="mini"
                                    @click="setRole(scope.row)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 size-change 每页最大数变化 current-change 页数变化 layout 功能组件-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1, 2, 5, 10]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
            ></el-pagination>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog
                title="添加用户"
                :visible.sync="dialogVisible"
                width="50%"
                @close="addDialogClosed"
        >
        <!-- 主体内容区域 -->
            <el-form
                    :model="addUserForm"
                    :rules="addUserFormRules"
                    ref="addUserFormRef"
                    label-width="70px"
                    class="demo-ruleForm"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="addUserForm.phone"></el-input>
                </el-form-item>
            </el-form>
            <!-- 内容底部区域 -->
            <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
        </el-dialog>

        <!-- 修改用户对话框 -->
        <el-dialog
                title="修改用户"
                :visible.sync="editDialogVisible"
                width="50%"
                @close="editDialogClosed"
        >
            <el-form
                    :model="editUserForm"
                    :rules="editUserFormRules"
                    ref="editUserFormRef"
                    label-width="70px"
                    class="demo-ruleForm"
            >
                <el-form-item label="用户名">
                    <el-input v-model="editUserForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="editUserForm.phone"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
        </el-dialog>

        <!-- 分配角色对话框 -->
        <el-dialog
                title="分配角色"
                :visible.sync="setRoleDialogVisible"
                @close="setRoleDialogClosed"
                width="50%"
        >
            <div>
                <p>当前的用户：{{ userInfo.username }}</p>
                <div>
                    <div v-for="(item,index) in userInfo.authorities" :key="index">
                        <p>当前的角色：{{ item.name }}</p>
                    </div>
                </div>
                <p>分配新角色:
                    <el-select v-model="selectRoleId" placeholder="请选择新角色">
                        <el-option
                                v-for="(item,index) in rolesList"
                                :key="index"
                                :label="item.name"
                                :value="item.name">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <div slot="footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo"
                >确 定
                </el-button
                >
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import Qs from 'qs'

    export default {
        data() {
            // 自定义邮箱校验规则
            var checkEmail = (rule, value, cb) => {
                const regEail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
                if (regEail.test(value)) {
                    return cb();
                }
                cb(new Error("请输入合法的邮箱"));
            };
            // 自定义手机号校验规则
            var checkMobile = (rule, value, cb) => {
                const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/;
                if (regMobile.test(value)) {
                    return cb();
                }
                cb(new Error("请输入合法的手机号"));
            };
            return {
                // 请求数据
                queryInfo: {
                    query: "",
                    pagenum: 1,
                    pagesize: 5
                },
                userlist: [],// 用户列表
                total: 0,// 最大数据记录
                dialogVisible: false,//对话框状态
                editDialogVisible: false,
                //添加表单信息
                addUserForm: {
                    username: "",
                    password: "",
                    email: "",
                    phone: ""
                },
                setRoleDialogVisible: false,
                //表单验证
                addUserFormRules: {
                    username: [
                        {required: true, message: "请输入用户名", trigger: "blur"},//必填项验证,失去焦点事件
                        {
                            require: true,
                            min: 3,
                            max: 10,
                            message: "用户名长度在 3 到 10 个字符",
                            trigger: "blur"
                        }
                    ],
                    password: [
                        {required: true, message: "请输入密码", trigger: "blur"},
                        {
                            require: true,
                            min: 6,
                            max: 15,
                            message: "密码长度在 6 到 15 个字符",
                            trigger: "blur"
                        }
                    ],
                    email: [
                        {required: true, message: "请输入邮箱", trigger: "blur"},
                        {validator: checkEmail, trigger: "blur"}
                    ],
                    phone: [
                        {required: true, message: "请输入手机", trigger: "blur"},
                        {validator: checkMobile, trigger: "blur"}
                    ]
                },
                editUserForm: {},
                editUserFormRules: {
                    email: [
                        {required: true, message: "请输入邮箱", trigger: "blur"},
                        {validator: checkEmail, trigger: "blur"}
                    ],
                    phone: [
                        {required: true, message: "请输入手机", trigger: "blur"},
                        {validator: checkMobile, trigger: "blur"}
                    ]
                },
                userInfo: "",
                rolesList: [
                    {name: 'ROLE_USER'},
                    {name: 'ROLE_ADMIN'}
                ],
                selectRoleId: ''
            };
        },
        methods: {
            //获取用户方法
            async getUserList() {
                const {data} = await this.$http.get("findByName", {
                    params: this.queryInfo
                });
                console.log(data)
                this.userlist = data.data.content;// 将返回数据赋值
                this.total = data.data.totalElements;// 总个数
            },
            // 监听pageSize改变的事件
            handleSizeChange(newSize) {
                this.queryInfo.pagesize = newSize;// 数据发生改变重新申请数据
                this.getUserList();
            },
            // 监听pageNum改变的事件
            handleCurrentChange(newPage) {
                this.queryInfo.pagenum = newPage;
                this.getUserList();// 数据发生改变重新申请数据
            },
            async userStateChanged(userinfo) {
                let params = Qs.stringify({
                    isActive: userinfo.isActive,
                    userId: userinfo.id
                })
                const {data} = await this.$http.put('/update/status', params);
                if (data.meta.status !== 200) {
                    this.$message.error("获取信息失败！");
                }
            },
            //监听添加用户方法
            addDialogClosed() {
                this.$refs.addUserFormRef.resetFields();
            },
            addUser() {
                this.$refs.addUserFormRef.validate(async valid => {
                    if (!valid) return;
                    const {data} = await this.$http.post("user/register", this.addUserForm);
                    console.log(data.meta.status)
                    if (data.meta.status !== 200) {
                        return this.$message.error("添加用户失败，手机号已注册！");
                    }
                    this.$message.success("添加用户成功！");
                    this.dialogVisible = false;
                    this.getUserList();
                });
            },
            //监听修改用户信息方法
            //显示对话框
            async showEditDialog(id) {
                const {data} = await this.$http.get(`select/user/${id}`);
                console.log(data)
                if (data.meta.status !== 200) {
                    return this.$message.error("查询用户失败！");
                }
                this.editUserForm = data.data;//查询出的用户信息反填到表单里
                this.editDialogVisible = true;//编辑对话框开启
            },
            //关闭窗口
            editDialogClosed() {
                this.$refs.editUserFormRef.resetFields();//重置信息
            },
            //确认修改
            editUser() {
                this.$refs.editUserFormRef.validate(async valid => {
                    if (!valid) return;
                    const {data} = await this.$http.post('user/update/m', this.editUserForm);
                    if (data.meta.status !== 200) {
                        return this.$message.error("修改用户信息失败！");
                    }
                    this.$message.success("修改成功！");
                    this.editDialogVisible = false;
                    this.getUserList();
                });
            },
            
            async setRole(userInfo) {
                /*const {data} = await this.$http.get("roles");
                if (data.meta.status !== 200) {
                    return this.$message.error(data.meta.msg);
                }
                this.rolesList = data.data*/
                this.userInfo = userInfo;
                this.setRoleDialogVisible = true;
            },
            async saveRoleInfo() {
                if (!this.selectRoleId) {
                    return this.$message.error('请选择要分配的角色！')
                }
                let Data = Qs.stringify({
                    id: this.userInfo.id,
                    role: this.selectRoleId
                })
                const {data} = await this.$http.put('update/role', Data)
                if (data.meta.status !== 200) {
                    return this.$message.error(data.meta.msg)
                }
                this.$message.success('分配角色成功！')
                this.getUserList();
                this.setRoleDialogVisible = false
            },
            setRoleDialogClosed() {
                this.selectRoleId = '',
                    this.userInfo = {}
            }
        },
        //create方法
        created() {
            this.getUserList();
        }
    };
</script>

<style lang="less" scoped></style>
